package pl.ptemich.eav.states;

import java.util.HashSet;
import java.util.Set;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.KeyListener;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;

import pl.ptemich.eav.constants.WorldLimits;
import pl.ptemich.eav.engine.WindowView;
import pl.ptemich.eav.engine.render.impl.RenderOptionsImpl;
import pl.ptemich.eav.sprites.AbstractStaticTile;
import pl.ptemich.eav.sprites.impl.Hero;
import pl.ptemich.eav.sprites.impl.Rock;

public class PlatformGameState extends BasicGameState implements KeyListener {

  private static final int STATE_ID = Double.valueOf(Math.random()).intValue(); 
  
  private Set<AbstractStaticTile> tiles;
  
  private Hero hero;
  
  private WindowView view;  
  
  @Override
  public int getID() {    
    return STATE_ID;
  }  
  
  @Override
  public void init(GameContainer container, StateBasedGame game)
      throws SlickException {
    tiles = new HashSet<AbstractStaticTile>();
    tiles.add(new Rock(100, 50));
    
    tiles.add(new Rock(150, 70));
    
    tiles.add(new Rock(200, 90));

    view = new WindowView(); 
    hero = new Hero(23, 23);
  }
  
  @Override
  public void render(GameContainer container, StateBasedGame game, Graphics graphics)
      throws SlickException {
    
    RenderOptionsImpl renderOptions = new RenderOptionsImpl(graphics, view);
    
    for (AbstractStaticTile tile : tiles) {
      tile.render(renderOptions);
    }
    
    hero.render(renderOptions);
  }
  
  @Override
  public void keyPressed(int key, char c) {    
    super.keyPressed(key, c);
    
    switch (key) {
      case Input.KEY_RIGHT:
        hero.moveRight();
        break;
      case Input.KEY_LEFT:
        hero.moveLeft();
        break;
      case Input.KEY_UP:
        hero.jump();
        break;
    } 
  }
  
@Override
  public void keyReleased(int key, char c) {
    super.keyReleased(key, c);
    switch (key) {
      case Input.KEY_RIGHT:
      case Input.KEY_LEFT:
        hero.stop();
        break;    
    }
  }  
  
  @Override
  public void update(GameContainer container, StateBasedGame game, int delta)
      throws SlickException {

    Input input = container.getInput();
    if (input.isKeyDown(Input.KEY_ESCAPE)) {
      container.exit();
    }


    
    hero.update(delta);
    
    hero.checkColission(tiles);
  }
  
}
